//
//  DLRiskEvaluationDetailVC.m
//  delongzhitou
//
//  Created by Mr.Wang on 2018/12/6.
//  Copyright © 2018 delongzhitou. All rights reserved.
//

#import "DLRiskEvaluationDetailVC.h"
#import "DLRiskEvaluationModel.h"
#import "DLRiskEvaluationAnsModel.h"
#import "DLRiskEvaluationQAView.h"
#import "DLRiskEvaluationChartView.h"
#import "DLRiskEvaluationResultVC.h"

@interface DLRiskEvaluationDetailVC()

@property (nonatomic, strong) NSMutableArray *dataSource;

@property (nonatomic, strong) DLRiskEvaluationQAView *qaView;

@property (nonatomic, strong) DLRiskEvaluationChartView *chartView;

@property (nonatomic, strong) UIButton *lastButton;

@property (nonatomic, strong) UIButton *nextButton;

@property (nonatomic, strong) UIButton *submitButton;

@property (nonatomic, assign) NSInteger currentQueIndex;

@property (nonatomic, strong) NSMutableArray *userChoiceDataSource;

@property (nonatomic, copy) NSString *currentAnsId;

@property (nonatomic, assign) BOOL isChooseAns;

@property (nonatomic, copy) NSString *selectKey;

@property (nonatomic, strong) NSArray *selectArray;

@end


@implementation DLRiskEvaluationDetailVC

- (void) viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self loadData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self setUpNav];
//    [self loadData];
}
- (void) loadData {
    
    self.currentQueIndex = 0;
    self.userChoiceDataSource = [NSMutableArray array];
    
    NSString *postUrl = HTTPGetRiskQuestion;
    NSDictionary *postDic = @{
                              };
    [[DLNetWorkManager shareInstance] requestWithMethod:DLRequestMethodPOST path:postUrl parameters:postDic success:^(id  _Nonnull responseObject) {
        if (kRequestSuccess(responseObject)) {
//            kShowRequestMsg(kSafeString(responseObject[@"message"]));
            NSArray *dataArr = responseObject[@"result"];
            if (dataArr.count > 0) {
                
                self.dataSource = [NSMutableArray array];
                for (NSInteger i = 0; i < dataArr.count; i++) {
                    DLRiskEvaluationModel *model = [DLRiskEvaluationModel new];
                    model.ansMutArr = [NSMutableArray array];
                    NSDictionary *queAndAnsDic = dataArr[i];
                    model.queId = [NSString stringWithFormat:@"%@", queAndAnsDic[@"id"]];
                    model.queSortOrder = [NSString stringWithFormat:@"%@", queAndAnsDic[@"sortorder"]];
                    model.queName = [NSString stringWithFormat:@"%@", queAndAnsDic[@"question"]];
                    
                    NSArray *ansArr = queAndAnsDic[@"answerVOList"];
                    if (ansArr.count > 0) {
                        
                        for (NSInteger i = 0; i < ansArr.count; i++) {
                            NSDictionary *ansDic = ansArr[i];
                            DLRiskEvaluationAnsModel *ansModel = [DLRiskEvaluationAnsModel new];
                            ansModel.ansId = [NSString stringWithFormat:@"%@", ansDic[@"id"]];
                            ansModel.ansSortOrder = [NSString stringWithFormat:@"%@", ansDic[@"sortorder"]];
                            ansModel.ansName = [NSString stringWithFormat:@"%@", ansDic[@"optionname"]];
                            ansModel.nextId = [NSString stringWithFormat:@"%@", ansDic[@"nextid"]];
                            [model.ansMutArr addObject:ansModel];
                        }
                    }
                    [self.dataSource addObject:model];
                }
                
                [self layoutSubControls];
                [self loadQaView];
            }
        } else {
            kShowRequestMsg(kSafeString(responseObject[@"message"]));
        }
    } failure:^(NSError * _Nonnull error) {
        NSLog(@"请求接口失败，错误是：%@", error);
    }];
}
- (void) layoutSubControls {
    
    [self.view.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    
    DLRiskEvaluationQAView *qaView = [[DLRiskEvaluationQAView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenSafeAreaHeight - kHeightNavigation - 200)];
    [self.view addSubview:qaView];
    self.qaView = qaView;
    
    qaView.chooseAnsBlock = ^(NSInteger ansId) {
        
        NSLog(@"选择的答案id是%ld", ansId);
        self.isChooseAns = YES;
        self.currentAnsId = [NSString stringWithFormat:@"%ld", ansId];
    };
    
    CGFloat buttonWidth = 80;
    CGFloat buttonHeight = 35;
    
    UIButton *lastButton = [UIButton buttonWithType:0];
    lastButton.frame = CGRectMake(qaView.left + 40, qaView.bottom + 30, buttonWidth, buttonHeight);
    [lastButton setTitle:@"上一题" forState:UIControlStateNormal];
    [lastButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    lastButton.titleLabel.font = kSystemFont(15);
    lastButton.backgroundColor = kDLBtnNormalBgColor;
    lastButton.layer.cornerRadius = 3;
    lastButton.clipsToBounds = YES;
    [self.view addSubview:lastButton];
    self.lastButton = lastButton;
    [lastButton addTarget:self action:@selector(lastButtonClick) forControlEvents:UIControlEventTouchUpInside];
    lastButton.hidden = YES;
    
    UIButton *nextButton = [UIButton buttonWithType:0];
    nextButton.frame = CGRectMake(qaView.right - 40 - buttonWidth, lastButton.top, buttonWidth, buttonHeight);
    [nextButton setTitle:@"下一题" forState:UIControlStateNormal];
    [nextButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    nextButton.titleLabel.font = kSystemFont(15);
    nextButton.backgroundColor = kDLBtnNormalBgColor;
    nextButton.layer.cornerRadius = 3;
    nextButton.clipsToBounds = YES;
    [self.view addSubview:nextButton];
    self.nextButton = nextButton;
    [nextButton addTarget:self action:@selector(nextButtonClick) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *submitButton = [UIButton buttonWithType:UIButtonTypeCustom];
    submitButton.frame = CGRectMake(25, kScreenSafeAreaHeight - kHeightNavigation - 100, kScreenWidth - 50, 35);
    [submitButton setTitle:@"提交" forState:UIControlStateNormal];
    [submitButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    submitButton.titleLabel.font = kSystemFont(15);
    submitButton.backgroundColor = kDLBtnNormalBgColor;
    submitButton.layer.cornerRadius = 3;
    submitButton.clipsToBounds = YES;
    [self.view addSubview:submitButton];
    self.submitButton = submitButton;
    [submitButton addTarget:self action:@selector(submitButtonClick) forControlEvents:UIControlEventTouchUpInside];
    submitButton.hidden = YES;
    
    DLRiskEvaluationChartView *chartView = [[DLRiskEvaluationChartView alloc] initWithFrame:qaView.frame];
    [self.view addSubview:chartView];
    self.chartView = chartView;
    chartView.hidden = YES;
    kWeakSelf;
    chartView.userSelectResultBlock = ^(NSString * _Nonnull selectKey, NSArray * _Nonnull selectValue) {
//        NSLog(@"%@====%@", selectKey, selectValue);
        weakSelf.selectKey = selectKey;
        weakSelf.selectArray = selectValue;
    };
    
}
- (void) loadQaView {
    
    self.isChooseAns = NO;
    
    DLRiskEvaluationModel *model = self.dataSource[self.currentQueIndex];
    self.qaView.qaModel = model;
}
- (void) submitButtonClick {
    
    NSDictionary *selectResultDic = @{@"selectKey" : self.selectKey,
                                      @"selectValue" : [self.selectArray arrayToJson]
                                      };
//    if (self.userChoiceDataSource.count < 8) {
//        [self.userChoiceDataSource addObject:selectResultDic];
//    } else {
//        [self.userChoiceDataSource removeLastObject];
//        [self.userChoiceDataSource addObject:selectResultDic];
//    }
    NSLog(@"传给后台的用户选择的答案是:%@", self.userChoiceDataSource);
    
    
    NSString *postUrl = HTTPSaveRiskAnswer;
    NSDictionary *postDic = @{@"result" : [self.userChoiceDataSource arrayToJson],
                              @"selectResult" : selectResultDic
                              };
    [[DLNetWorkManager shareInstance] requestWithMethod:DLRequestMethodPOST path:postUrl parameters:postDic success:^(id  _Nonnull responseObject) {
        if (kRequestSuccess(responseObject)) {
            kShowRequestMsg(kSafeString(responseObject[@"message"]));
            
        } else {
            kShowRequestMsg(kSafeString(responseObject[@"message"]));
            
        }
        DLRiskEvaluationResultVC *rervc = [DLRiskEvaluationResultVC new];
//        rervc.xxx = responseObject[xxxxx];
        [self.navigationController pushViewController:rervc animated:YES];
    } failure:^(NSError * _Nonnull error) {
        NSLog(@"请求接口失败，错误是：%@", error);
    }];
}

- (void) configUserChoiceDataSource{
    
    NSString *currentQueId = @"";
    NSString *currentQueName = @"";
    NSString *currentAnsId = @"";
    NSString *currentAnsName = @"";
    
    DLRiskEvaluationModel *model = self.dataSource[self.currentQueIndex];
    currentQueId = model.queId;
    currentQueName = model.queName;
    currentAnsId = self.currentAnsId;
    
    NSArray *ansArr = model.ansMutArr;
    for (NSInteger i = 0; i < ansArr.count; i++) {
        DLRiskEvaluationAnsModel *model = ansArr[i];
        
        if ([currentAnsId isEqualToString:model.ansId]) {
            currentAnsName = model.ansName;
        }
    }
    NSLog(@"%@", currentQueId);
    NSLog(@"%@", currentQueName);
    NSLog(@"%@", currentAnsId);
    NSLog(@"%@", currentAnsName);
    NSDictionary *dic = @{
                          @"questionid" : currentQueId,
                          @"questionname" : currentQueName,
                          @"answerid" : currentAnsId,
                          @"answername" : currentAnsName
                          };
    [self.userChoiceDataSource addObject:dic];
}
- (void) nextButtonClick {
    
    if (self.isChooseAns == NO) {
        kShowRequestMsg(@"请选择一个答案！");
        return;
    }
    
    //点击先保存当前题的状态
    [self configUserChoiceDataSource];
    
    self.currentQueIndex +=1;
    if (self.currentQueIndex == 7) {
        
        self.lastButton.hidden = NO;
        self.nextButton.hidden = YES;
        self.submitButton.hidden = NO;
        
        self.qaView.hidden = YES;
        self.chartView.hidden = NO;
        self.chartView.titleCount = 7;
        NSString *path = [[NSBundle mainBundle] pathForResource:@"chart.json" ofType:nil];
        NSData *data = [NSData dataWithContentsOfFile:path];
        NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
        self.chartView.chartDic = jsonDic;
    } else {
        self.lastButton.hidden = NO;
        self.nextButton.hidden = NO;
        self.submitButton.hidden = YES;
        [self loadQaView];
    }
    
}
- (void) lastButtonClick {
    
//    //不是最后一题的时候，点击上一题，到上一题之后在移除上一题选择的答案，所以要先--，因为保存答案是点击下一题的时候保存的；如果是最后一题，有默认答案，不需要点下一题的按钮，所以答完第七题点了下一步，相当于一次性给数组加了两个元素（第七题和第八题），所以当currentQueIndex==7的时候点击上一题，要移除最后两个元素，也就是移除两次。
//    if (self.currentQueIndex == 7) {
//        [self.userChoiceDataSource removeLastObject];
//    }
    self.currentQueIndex -=1;
    
    [self.userChoiceDataSource removeObjectAtIndex:self.currentQueIndex];
    
    self.chartView.hidden = YES;
    self.qaView.hidden = NO;
    
    if (self.currentQueIndex == 0) {
        self.lastButton.hidden = YES;
        self.nextButton.hidden = NO;
        self.submitButton.hidden = YES;
    } else {
        self.lastButton.hidden = NO;
        self.nextButton.hidden = NO;
        self.submitButton.hidden = YES;
    }
    [self loadQaView];
}
- (void) setUpNav {
    self.titleView.title = @"风险测评";
}
@end
